<?php

namespace App\Models\Common;

use Illuminate\Support\Arr;

class ApiResponse
{
    const RESP_CODE_SUCCESS = 200;
    const CODE_HEADER_ERR = 300;
    const RESP_CODE_UNAUTHENTICATED = 401;
    const RESP_CODE_AUTHORIZATION = 403;
    const RESP_CODE_FAILURE = 500;
    const CODE_INVALID_ARGUMENT = 501;
    const CODE_NO_ABILITY = 502;
    const CODE_TIME_LIMIT = 503;
    const RESP_CODE_MQTT_SERVICE_ERROR = 555;

    const RESP_CODE_CN_MAPPING = [
        self::RESP_CODE_SUCCESS => '操作成功',
        self::RESP_CODE_FAILURE => '操作失败',
        self::RESP_CODE_UNAUTHENTICATED => '请求认证失败',
        self::CODE_HEADER_ERR => '头部参数错误',
        self::CODE_INVALID_ARGUMENT => '无效的请求参数',
        self::CODE_NO_ABILITY => '无操作权限',
        self::CODE_TIME_LIMIT => '操作过于频繁',
        self::RESP_CODE_AUTHORIZATION => '禁止访问',
        self::RESP_CODE_MQTT_SERVICE_ERROR => 'mqtt服务异常'
    ];

    public static function success($returnDat = null, $returnMsg = ''): array
    {
        return self::return($returnMsg, $returnDat);
    }

    public static function fail(string $returnMsg = '', $returnDat = null, int $responseCode = self::RESP_CODE_FAILURE): array
    {
        return self::return($returnMsg, $returnDat, $responseCode);
    }

    public static function return(string $returnMsg = '', $returnDat = null, int $respCode = self::RESP_CODE_SUCCESS):array
    {
        $msgContent = Arr::get(self::RESP_CODE_CN_MAPPING, $respCode) ?: self::RESP_CODE_CN_MAPPING[self::RESP_CODE_SUCCESS];

        if ($returnMsg) {
            $msgContent .= ':' . $returnMsg;
        }

        if (!$returnDat) {
            $returnDat = '';
        }

        return [
            'code' => $respCode,
            'desc' => $msgContent,
            'data' => $returnDat,
            'timestamp' => now()->toDateTimeString()
        ];
    }
}
